package com.wuli.auth.controller;

import com.wuli.auth.common.Dto.UserDto;
import com.wuli.auth.common.Vo.UserLoginVo;
import com.wuli.auth.common.Vo.UserRegVo;
import com.wuli.auth.common.model.R;
import com.wuli.auth.config.MD5utilConfig;
import com.wuli.auth.entity.User;
import com.wuli.auth.feignClient.GatewayFeign;
import com.wuli.auth.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@Api(tags = "用户管理")
@RestController
@RequestMapping("/auth/User")
public class UserController {
    @Autowired
    GatewayFeign gatewayFeign;


    @Autowired
    UserService userService;

    @ApiOperation("用户注册")
    @PostMapping("/Register")
    public R<UserDto> Reg(@RequestBody UserRegVo userRegVo){
            User user = userService.GetUserByPhone(userRegVo.getPhone());
            if(user!=null){
                return new R().Error("该手机号已经被注册");
            }
            else {
                user = new User();
                user.username = userRegVo.getUsername();
                user.password= MD5utilConfig.code(userRegVo.getPassword());
                user.phone= userRegVo.getPhone();
                userService.Add(user);
                user =userService.GetUserByPhone(userRegVo.phone);
                UserDto userDto=new UserDto();
                BeanUtils.copyProperties(user,userDto);
                return new R().Success(userDto);
            }
    }

    @ApiOperation("登入接口")
    @PostMapping("/Login")
    public R<UserDto> login(@RequestBody UserLoginVo userLoginVo){
        User user =userService.GetUserByPhone(userLoginVo.phone);
        if (user!=null && user.password.equals(MD5utilConfig.code(userLoginVo.password))){
            String token=gatewayFeign.Token(user.phone);
            user.setToken(token);
            Date createTime = new Date();
            user.setExpirationTime(new Date(createTime.getTime() +  60*60*24));
            userService.UpdateToken(user);
            UserDto userDto=new UserDto();
            BeanUtils.copyProperties(user,userDto);
            return new R().Success(userDto);
        }
        return new R().Success("手机号或者密码错误！");
    }

    //只有超级管理员有该权限，即roleId为3的
    @ApiOperation("修改用户角色")
    @GetMapping("/UpdateUserRole/{id}/{roleId}")
    public R UpdateUserRole(@PathVariable Integer id,@PathVariable Integer roleId){
        userService.UpdateUserRole(id,roleId);
        return new R().Success("修改角色成功");
    }

}
